# -*- coding: utf-8 -*-
from flask import Flask, request, jsonify
from flask_cors import CORS
from http.client import HTTPException

from common.Result import Result
from resource.core.chatbot_graph import ChatBotGraph

app = Flask(__name__)
CORS(app)  # 解决跨域问题，允许所有来源的跨域请求

# 初始化问答系统
handler = ChatBotGraph()

@app.route('/')
def hello_world():
    return 'Hello World'

@app.route('/api/chat', methods=['POST'])
def chat():
    json = request.get_json()
    question = json['question']
    print(f'通过网络请求得到的问题：{question}')
    answer = handler.chat_main(question)
    print(f'这里是得到的答案:{answer}')
    return jsonify(Result.success(answer).to_dict())

# 全局异常处理
@app.errorhandler(Exception)
def handle_exception(e):
    print(e)
    if isinstance(e, HTTPException):
        return jsonify(Result.error(f"HTTP错误: {e.description}").to_dict()), e.code
    else:
        return jsonify(Result.error(f"服务器内部错误: {str(e)}").to_dict()), 500

if __name__ == '__main__':
    app.run(debug=True) 